﻿@page "/HtProcessing"
@rendermode InteractiveServer
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using HtERP.Data
@using Microsoft.AspNetCore.Components.QuickGrid
@using ClosedXML.Excel
@inject IJSRuntime JS
@attribute [Authorize]

<PageTitle>HtProcessing</PageTitle>

<div>
    <strong><font size="5" style="color:#016f5e">后道加工</font></strong>
    <em>（共: <strong>@numResults() </strong>条，数量: <strong>@TotalQuantity() </strong>，价格: <strong>@Totalprice()</strong>元。）</em>
    每页显示条数:
    <select @bind="@pagination.ItemsPerPage">
        <option>50</option>
        <option>200</option>
        <option>500</option>
        <option>1000</option>
        <option>2000</option>
    </select>

</div>

<div>
    <input @bind="date1" id="tt" type="date" style="width:120px" />
    <input @bind="date2" id="tt" type="date" style="width:120px" />
    <input type="search" autofocus @bind="nameFilter" placeholder="客户..." style="width:120px" />
    <input type="search" autofocus @bind="nameFilter1" placeholder="工作名..." style="width:120px" />
    <button class="btn btn-primary" @onclick="查询">查询</button>
    <button class="btn btn-primary" @onclick="清空搜索项">清空搜索项</button>
    <button class="btn btn-primary" @onclick="DownloadExcel">下载Excel</button>
</div>

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
     <div>
        <QuickGrid Items="items" Theme="corporate" class="table" Pagination="@pagination">
       
            <PropertyColumn Property="@(c => c.编号)" Sortable="true" Align="Align.Right" Title="编号" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true" />
            <PropertyColumn Property="@(c => c.打印类型)" Sortable="true" Align="Align.Right" Title="印类型" />
            <TemplateColumn Title="日期" SortBy="@日期排序" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                    <input id="date1" type="date" @bind="@(context.日期)" style="width:98px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="客户" SortBy="@客户排序" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                    <input type="text" @bind="@(context.客户)" @onclick="khLoadList" list="options" style="min-width:98px" @bind:after="@(() => 更新数据(context))">
                        <datalist id="options">
                        <option value="现金"></option>
                        <option value="临时"></option>
                        @if(kh!=null) foreach (var forecast in kh)
                            {
                                <option value="@forecast.客户ID"></option>
                            }
                            <!-- 更多选项 -->
                        </datalist>
            </TemplateColumn>
           
            <TemplateColumn Title="工作名" SortBy="@品名排序" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                    <input type="text" @bind=@(context.文件或工作名) style="min-width:168px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="长" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                    <input  type="number" @bind="@(context.长)" style="text-align: right; width:40px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="宽"  Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                    <input  type="number" @bind="@(context.宽)" style="text-align: right; width:40px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="数量" SortBy="@张数排序" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="number" @bind="@(context.数量)" style="text-align: right; width:48px" @bind:after="@(() => 计算后道价格(context))" />
            </TemplateColumn>
           
            <TemplateColumn Title="要求" SortBy="@要求排序" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                    <input type="text" @bind="@(context.要求)" style="min-width:158px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>

            <TemplateColumn Title="急" Align="Align.Center">
                <input id="Checkbox2" type="checkbox" @bind=@(context.急) style="width:18px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>

            <TemplateColumn Title="送货地点" SortBy="@送货排序" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                    <input id="textsh" type="text" @bind="@(context.送货地点)" style=" min-width:66px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="完成" SortBy="@rankSort" Align="Align.Center">
                <input id="Checkbox1" type="checkbox" @bind=@(context.已经发送) style="width:28px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title=" "   Align="Align.Center">
                <input id="Checkbox1" type="checkbox" @bind=@(context.覆膜) style="width:18px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="覆膜单价" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="number" @bind="@(context.覆膜单价)" style="text-align: right; width:50px" @bind:after="@(() => 覆膜计算(context))" />
            </TemplateColumn>
            <TemplateColumn Title=" "   Align="Align.Center">
                <input id="Checkbox1" type="checkbox" @bind=@(context.切割) style="width:18px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="切割单价" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="number" @bind="@(context.切割单价)" style="text-align: right; width:50px" @bind:after="@(() => 切割计算(context))" />
            </TemplateColumn>
            <TemplateColumn Title=" "   Align="Align.Center">
                <input id="Checkbox1" type="checkbox" @bind=@(context.装订) style="width:18px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="装订单价" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="number" @bind="@(context.装订单价)" style="text-align: right; width:50px" @bind:after="@(() => 装订计算(context))" />
            </TemplateColumn>
            <TemplateColumn Title="其他单价" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="number" @bind="@(context.其他单价)" style="text-align: right; width:50px" @bind:after="@(() => 计算后道价格(context))" />
            </TemplateColumn>
            <TemplateColumn Title="其他加工" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="text" @bind=@(context.其他加工) style="min-width:68px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="加工费" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="number"
                       style="text-align: right; width:68px"
                       value="@(context.加工费?.ToString("F2") ?? "NULL")"
                       @onchange="@(e => context.加工费 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                       @onblur="@(() => 合计后道价格(context))" />
            </TemplateColumn>
            <TemplateColumn Title="其他费用" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="number"
                       style="text-align: right; width:68px"
                       value="@(context.其他费用?.ToString("F2") ?? "NULL")"
                       @onchange="@(e => context.其他费用 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                       @onblur="@(() => 合计后道价格(context))" />
            </TemplateColumn>
            <TemplateColumn Title="应收" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="number"
                       style="text-align: right; width:78px"
                       value="@(context.应收?.ToString("F2") ?? "NULL")"
                       @onchange="@(e => context.应收 = decimal.TryParse(e.Value?.ToString(), out decimal d) ? d : 0)"
                       @onblur="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="结清" Align="Align.Center">
                <input id="Checkbox3" type="checkbox" @bind=@(context.结清) style="width:18px" disabled />
            </TemplateColumn>
            <TemplateColumn Title="制作员" SortBy="@制作排序" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input type="text" @bind="@(context.制作员1)" @onclick="ygLoadList" list="ygoptions" style="width:68px" @bind:after="@(() => 更新数据(context))">
                <datalist id="ygoptions">
                    @if (yglist != null) foreach (var foryg in yglist)
                        {
                            <option value="@foryg.姓名"></option>
                        }
                </datalist>
            </TemplateColumn>

            <TemplateColumn Title="备注" SortBy="@备注排序" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <input id="Text1" type="text" @bind="@(context.备注)" style="min-width: 66px" @bind:after="@(() => 更新数据(context))" />
            </TemplateColumn>
            <TemplateColumn Title="" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true">
                <button @onclick="@(() => ShowDeleteEvent(context))" style="color:red">删</button>
            </TemplateColumn>

        </QuickGrid>
         <Paginator State="@pagination" />
        <p> <button class="btn btn-primary" @onclick="新建后道项目">新建</button> </p>
    </div>

}

@if (ShowDelete)
{
    <div class="custom-dialog" @onclick:stopPropagation>
        <div class="dialog-content">
            <h3> 是否确定要删除：</h3>
            <h4> @aa</h4>
            <p><button class="dialog-button" @onclick="Deleteit">确定删除</button> <button class="dialog-button" @onclick="HideDeleteEvent">取消</button></p>
        </div>
    </div>
}

@code {
    PaginationState pagination = new PaginationState { ItemsPerPage = 200 };

    [CascadingParameter]
    private Task<AuthenticationState>? authenticationState { get; set; }

    AuthState? AuthState;

    DateTime date1 = DateTime.Now.AddDays(-1);
    DateTime date2 = DateTime.Now;

    string nameFilter = string.Empty;
    string nameFilter1 = string.Empty;

    private 后道加工[]? forecasts;
    private IQueryable<后道加工>? items;

    GridSort<后道加工> rankSort = GridSort<后道加工>.ByDescending(x => x.已经发送);
    GridSort<后道加工> 日期排序 = GridSort<后道加工>.ByAscending(x => x.日期);
    GridSort<后道加工> 客户排序 = GridSort<后道加工>.ByAscending(x => x.客户);
    GridSort<后道加工> 品名排序 = GridSort<后道加工>.ByAscending(x => x.文件或工作名);
    GridSort<后道加工> 张数排序 = GridSort<后道加工>.ByAscending(x => x.数量);
    GridSort<后道加工> 价格排序 = GridSort<后道加工>.ByAscending(x => x.应收);
    GridSort<后道加工> 要求排序 = GridSort<后道加工>.ByAscending(x => x.要求);
    GridSort<后道加工> 送货排序 = GridSort<后道加工>.ByAscending(x => x.送货地点);
    GridSort<后道加工> 制作排序 = GridSort<后道加工>.ByAscending(x => x.制作员1);
    GridSort<后道加工> 备注排序 = GridSort<后道加工>.ByAscending(x => x.备注);

    public int numResults()
    {
        int Count = items.Count();
        return Count;
    }
    public float? TotalQuantity()  //数量合计
    {
        float? total = items.Sum(item => item.数量);
        return total;
    }
    public decimal? Totalprice()  //价格合计
    {
        decimal? total = items.Sum(item => item.应收);
        return total;
    }

    private 客户[]? kh;
    private void khLoadList()
    {
        kh = HongtengDbCon.Db.Queryable<客户>().Where(it => it.IsDelete == false).ToArray();
    }

    public 员工[] yglist;
    private void ygLoadList()
    {
        yglist = HongtengDbCon.Db.Queryable<员工>().Where(it => it.是否已离职 != true).ToArray();
    }

    protected override async Task OnInitializedAsync()
    {

        AuthState = authenticationState?.Result as AuthState;
        forecasts = HongtengDbCon.Db.Queryable<后道加工>().Where(it => it.日期.Value.Date == date2.Date).Where(it => it.IsDelete == false).ToArray();
        items = forecasts.AsQueryable();
        await InvokeAsync(StateHasChanged);
    }


    private void 查询()
    {

        DateTime d1 = date1;
        DateTime d2 = date2;

        if (date2 < date1)
        {
            d1 = date2;
            d2 = date1;
        }

        forecasts = HongtengDbCon.Db.Queryable<后道加工>().Where(it => it.IsDelete == false)
                .WhereIF(true, it => it.日期.Value.Date >= d1.Date && it.日期.Value.Date <= d2.Date)
                .WhereIF(!string.IsNullOrEmpty(nameFilter), it => it.客户.Contains(nameFilter))
                .WhereIF(!string.IsNullOrEmpty(nameFilter1), it => it.文件或工作名.Contains(nameFilter1)).ToArray();
        items = forecasts.AsQueryable();
    }

    private void 清空搜索项()
    {
        nameFilter = string.Empty;
        nameFilter1 = string.Empty;
    }
    
    private void 新建后道项目()
    {
        var ddd = HongtengDbCon.Db.Insertable(new 后道加工() { 客户 = "", 日期 = DateTime.Now, 制作员1 = AuthState?.UserName }).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntity();
        var dda = forecasts.ToList();
        dda.Add(ddd);
        forecasts = dda.Where(it => it.IsDelete == false).ToArray();
        items = forecasts.AsQueryable();
    }

    private void 更新数据(后道加工 p)
    {
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(p).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
    }

    //弹出窗口-软删除一条
    string? aa;
    public 后道加工? pp;
    public bool ShowDelete { get; set; }
    private void HideDeleteEvent()
    {
        ShowDelete = false;
    }
    private void ShowDeleteEvent(后道加工 p)
    {
        pp = p;
        aa = pp.编号 + "，" + pp.客户 + "【" + pp.文件或工作名 + "】";
        ShowDelete = true;
    }
    private void Deleteit()
    {
        pp.IsDelete = true;
        HongtengDbCon.Db.Updateable(forecasts).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
        items = forecasts.Where(it => it.IsDelete == false).AsQueryable();
        ShowDelete = false;
    }

    //后道加工价格计算
    private void 覆膜计算(后道加工 processing)
    {
        if (processing.覆膜单价 > 0)
        {
            processing.覆膜 = true;
        }
        计算后道价格(processing);
    }
    private void 切割计算(后道加工 processing)
    {
        if (processing.切割单价 > 0)
        {
            processing.切割 = true;
        }
        计算后道价格(processing);
    }
    private void 装订计算(后道加工 processing)
    {
        if (processing.装订单价 > 0)
        {
            processing.装订 = true;
        }
        计算后道价格(processing);
    }
    private void 计算后道价格(后道加工 processing) //计算后道加工价格
    {
        if (processing.其他单价 == null)
        {
            processing.其他单价 = 0;
        }
        if (processing.覆膜单价 == null)
        {
            processing.覆膜单价 = 0;
        }
        if (processing.切割单价 == null)
        {
            processing.切割单价 = 0;
        }
        if (processing.装订单价 == null)
        {
            processing.装订单价 = 0;
        }
        if (processing.数量 == null)
        {
            processing.数量 = 0;
        }
        if (processing.其他费用 == null)
        {
            processing.其他费用 = 0;
        }
        if (processing.设计制作费 == null)
        {
            processing.设计制作费 = 0;
        }
        processing.加工费 = (processing.其他单价 + processing.覆膜单价 + processing.切割单价 + processing.装订单价) * ((decimal)processing.数量.Value);
        if (processing.加工费 < 10 && processing.加工费 > 0)
        {
            processing.加工费 = 10;
        }
        processing.应收 = processing.其他费用 + processing.加工费 + processing.设计制作费;
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(forecasts).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand(); //更新数据
    }
    private void 合计后道价格(后道加工 processing) //计算后道加工价格
    {
        if (processing.其他费用 == null)
        {
            processing.其他费用 = 0;
        }
        if (processing.加工费 == null)
        {
            processing.加工费 = 0;
        }
        if (processing.设计制作费 == null)
        {
            processing.设计制作费 = 0;
        }
        processing.应收 = processing.其他费用 + processing.加工费 + processing.设计制作费;
        HongtengDbCon.Db.CurrentConnectionConfig.MoreSettings.IsCorrectErrorSqlParameterName = true; //局部生效兼容模式
        HongtengDbCon.Db.Updateable(forecasts).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand(); //更新数据
    }
    // 导出Excel文件
    public async Task DownloadExcel()
    {
        using (XLWorkbook workbook = new XLWorkbook())
        {
            IXLWorksheet worksheet = workbook.AddWorksheet("Mysheet");

            worksheet.Cell(1, 1).Value = "编号";
            worksheet.Cell(1, 2).Value = "日期";
            worksheet.Cell(1, 3).Value = "客户";
            worksheet.Cell(1, 4).Value = "工作名";
            worksheet.Cell(1, 5).Value = "数量";
            worksheet.Cell(1, 6).Value = "价格";
            worksheet.Cell(1, 7).Value = "要求";
            worksheet.Cell(1, 8).Value = "送货地址";
            worksheet.Cell(1, 9).Value = "制作员";
            worksheet.Cell(1, 10).Value = "备注";

            worksheet.Row(1).Style.Font.Bold = true;


            int row = 2;
            foreach (var forzz in forecasts)
            {
                worksheet.Cell(row, 1).Value = forzz.编号.ToString();
                worksheet.Cell(row, 2).Value = forzz.日期;
                worksheet.Cell(row, 3).Value = forzz.客户;
                worksheet.Cell(row, 4).Value = forzz.文件或工作名;
                worksheet.Cell(row, 5).Value = forzz.数量;
                worksheet.Cell(row, 6).Value = forzz.应收;
                worksheet.Cell(row, 7).Value = forzz.要求;
                worksheet.Cell(row, 8).Value = forzz.送货地点;
                worksheet.Cell(row, 9).Value = forzz.制作员1;
                worksheet.Cell(row, 10).Value = forzz.备注;
                row++;
            }

            // 创建内存流用于保存工作簿
            using (var memoryStream = new MemoryStream())
            {
                // 将工作簿保存到内存流中
                workbook.SaveAs(memoryStream);

                // 重置内存流的位置，以确保从头开始读取
                memoryStream.Position = 0;

                // 这里可以将内存流进行进一步处理，例如发送为电子邮件附件或者作为API响应返回等
                var fileName = "后道加工" + DateTime.Now.ToString() + ".xlsx";

                using var streamRef = new DotNetStreamReference(stream: memoryStream);

                await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
            }
        }

    }


}
